package cc.chinagps.gateway.client.packet.down;

import cc.chinagps.gateway.client.bean.DieselRealTimeInfo;
import cc.chinagps.gateway.client.bean.ObdBaseInfo;
import cc.chinagps.gateway.client.bean.ObdEngineDataStreamInfo;
import cc.chinagps.gateway.client.bean.TerminalType;
import cc.chinagps.gateway.client.packet.BasePacket;
import cc.chinagps.gateway.client.packet.base.PacketAdapter;
import cc.chinagps.gateway.util.CommonUtils;
import io.netty.buffer.ByteBuf;
import io.netty.buffer.Unpooled;
import lombok.Data;
import lombok.EqualsAndHashCode;


@EqualsAndHashCode(callSuper = true)
@Data
public class Packet02 extends PacketAdapter {
    private byte[] sendTime = new byte[6];
    private short serialNo;
    private byte infoType;
    private byte[] collectTime = new byte[6];
    private DieselRealTimeInfo realTimeInfo;

    public Packet02(BasePacket basePacket) {
        super(basePacket);
    }

    public void decodeBusinessData(byte[] data) throws Exception {
        ByteBuf buf = Unpooled.copiedBuffer(data);
        TerminalType terminalType = TerminalType.find(getBasePacket().getDeviceInfo().getTerminalType());
        switch (terminalType) {
            case ELECTRONIC_LABEL:
                break;
            case OBD:
                realTimeInfo = new DieselRealTimeInfo();
                buf.readBytes(sendTime);
                serialNo = buf.readShort();
                infoType = buf.readByte();
                buf.readBytes(collectTime);
                if (infoType == 0x01) {
                    ObdBaseInfo obdBaseInfo = new ObdBaseInfo();
                    obdBaseInfo.decode(buf, 0);
                    realTimeInfo.setObdBaseInfo(obdBaseInfo);
                }
                if (infoType == 0x02) {
                    ObdEngineDataStreamInfo engineDataStreamInfo = new ObdEngineDataStreamInfo();
                    engineDataStreamInfo.parse(buf);
                    realTimeInfo.setDataStreamInfo(engineDataStreamInfo);
                }
                break;
            default:
                throw new Exception("terminal type error,terminalType:" + terminalType);
        }
    }

    @Override
    public void decodeBusinessData() throws Exception {
        byte[] data = basePacket.getMsgBody();
        decodeBusinessData(data);
    }

    @Override
    public byte[] encodeBussinessData() throws Exception {
        ByteBuf buf = Unpooled.buffer(16);
        buf.writeBytes(sendTime);
        buf.writeShort(serialNo);
        buf.writeByte(infoType);
        buf.writeBytes(collectTime);
        ObdBaseInfo obdBaseInfo = realTimeInfo.getObdBaseInfo();
        if (infoType == 0x01 && obdBaseInfo != null) {
            buf.writeBytes(obdBaseInfo.encode());
        }
        if (infoType == 0x02) {
            buf.writeBytes(realTimeInfo.getDataStreamInfo().encode());
        }
        return CommonUtils.getByteArray(buf);
    }
}
